package wxpay

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.github.uiautomator.R
import com.google.gson.Gson
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okio.IOException

class WXPayActivity : Activity(), IWXAPIEventHandler {

    val tag = "WXPayActivity"
    lateinit var context: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
        setContentView(R.layout.activity_wxpay)
        initView()
    }

    private fun initView() {
        findViewById<View>(R.id.payButton).setOnClickListener {
            pay()
        }
    }

    private fun pay() {

        val params = HashMap<String, Any>()
        params["price"] = 1
        params["goodsName"] = "圣诞节礼物"
        val data = Gson().toJson(params)
        sendPayRequest(data)

        Toast.makeText(this, "启动微信支付", Toast.LENGTH_SHORT).show()
    }

    //
    fun sendPayRequest(json: String) {
        // 创建OkHttpClient实例
        val client = OkHttpClient()

        // 创建RequestBody
        val body = RequestBody.create(
            "application/json; charset=utf-8".toMediaType(), // 使用 toMediaType() 来替代 MediaType.parse()
            json
        )

        // 创建请求
        val request = Request.Builder()
            .url("http://120.232.74.41:5557/wechat.php")
            .post(body)  // 使用POST方法
            .build()

        // 发起请求并处理响应
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败时的处理
                e.printStackTrace()
                Log.i(tag, "请求失败: ${e}")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    // 请求成功，处理响应
                    val responseData = response.body?.string()
                    Log.i(tag, "响应数据: $responseData")

                    val payReq = Gson().fromJson(responseData, PayReq::class.java)
                    openWXPay(payReq)
                } else {
                    // 请求失败，处理错误
                    Log.i(tag, "请求失败，错误码: ${response.code}")
                }
            }
        })
    }

    private fun openWXPay(payReq: PayReq) {
        Log.i(tag, "openWXPay")
        WXPay.APP_ID = payReq.appid
        val wxPay = WXPay(context)
        wxPay.pay(payReq.partnerid, payReq.prepayid, payReq.noncestr, payReq.timestamp, payReq.sign)
    }

    companion object {
        fun start(context: Context) {
            context.startActivity(Intent(context, WXPayActivity::class.java))
        }
    }

    override fun onReq(baseResp: BaseReq) {

    }

    override fun onResp(baseResp: BaseResp) {
        Log.i(tag, "onResp:$baseResp")
    }


    data class PayReq(
        val appid: String,
        val partnerid: String,
        val prepayid: String,
        val noncestr: String,
        val timestamp: String,
        val sign: String,
    );

}